package mysql_sync

import (
	"context"
	"gc-rds-ha/internal/dao"
	"gc-rds-ha/internal/dao/mysql_sync/mysql_servers"
	grpcError "gc-rds-ha/internal/error"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type MysqlServers struct {
	ID          int
	HostGroupID int
	HostName    string
	Port        uint32

	Tx *gorm.DB `gorm:"-"`
}

// TableName 表名
func (d *MysqlServers) TableName() string {
	name := "mysql_servers"
	return name
}

// Model 模型
func (d *MysqlServers) Model() *gorm.DB {
	db := dao.DB_PROXYSQL
	if d.Tx != nil {
		db = d.Tx
	}

	return db.Table(d.TableName()).Model(d)
}

// Create 创建
func (d *MysqlServers) Create(ctx context.Context, datas []*MysqlServers) error {
	m := d.Model()
	//db.Clauses(
	//	gorm.Expr("ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age)"),
	//).Create(&user)
	for _, data := range datas {
		if err := m.FirstOrCreate(data, data).Error; err != nil {
			log.WithFields(log.Fields{"err": err, "data": data}).Error("m.Create(data) error")
		}
		mysqlServersRecord := mysql_servers.MysqlServersRecord{
			HostGroupID: data.HostGroupID,
			HostName:    data.HostName,
			Port:        data.Port,
		}
		//本地操作记录
		if err := mysqlServersRecord.Create(); err != nil {
			return grpcError.GrpcErrDB
		}
	}
	//if err := m.Exec("LOAD MYSQL SERVERS TO RUNTIME;").Error; err != nil {
	//	log.WithFields(log.Fields{"err": err}).Error("LOAD To Runtime error")
	//}
	//if err := m.Exec("SAVE MYSQL SERVERS TO DISK"); err != nil {
	//	log.WithFields(log.Fields{"err": err}).Error("SAVE To Disk error")
	//}
	return nil
}

// Get 获取
func (d *MysqlServers) Get(ctx context.Context) error {
	m := d.Model()

	if d.ID != 0 {
		m = m.Where("id = ?", d.ID)
	}

	if err := m.Order("id asc").First(d); err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("m.Create(d) error")
	}
	return nil
}
